package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.admin.mapper.UserInfoMapper;
import com.tanhua.admin.mapper.UsersMapper;
import com.tanhua.model.domain.Analysis;
import com.tanhua.model.domain.Log;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.DateVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserStatisticsVo;
import com.tanhua.model.vo.YearStatisticsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class DashBoardService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private AnalysisMapper analysisMapper;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;


    //概要统计信息
    public UserStatisticsVo summaryInfo() {
        UserStatisticsVo userStatisticsVo = new UserStatisticsVo();
        String month = new SimpleDateFormat("yyyy-MM-dd").format(this.getMonthStartTime());
        String week = new SimpleDateFormat("yyyy-MM-dd").format(this.getWeekStartTime());
        String todayStart = new SimpleDateFormat("yyyy-MM-dd").format(this.getTodayStartTime());
        String todayEnd = new SimpleDateFormat("yyyy-MM-dd").format(this.getTodayEndTime());
        String yesterdayStart = new SimpleDateFormat("yyyy-MM-dd").format(this.getYesterdayStartTime());
        String yesterdayEnd = new SimpleDateFormat("yyyy-MM-dd").format(this.getYesterdayEndTime());
        //累计用户
        Integer count = analysisMapper.selectCount(null);
        userStatisticsVo.setCumulativeUsers(count);
        //过去30天活跃用户
        QueryWrapper<Log> queryMonthActive = new QueryWrapper<>();
        queryMonthActive.between("log_time", month, todayEnd);
        Integer monthCount = this.logMapper.selectCount(queryMonthActive);
        userStatisticsVo.setActivePassMonth(monthCount);
        //过去7天活跃用户
        QueryWrapper<Log> queryWeekActive = new QueryWrapper<>();
        queryWeekActive.between("log_time", week, todayEnd);
        Integer weekCount = logMapper.selectCount(queryWeekActive);
        userStatisticsVo.setActivePassWeek(weekCount);
        //今日新增用户
        List<UserInfo> userInfoList = userInfoMapper.selectList(null);
        if (CollUtil.isEmpty(userInfoList)) {
            throw new BusinessException(ErrorResult.error().getErrMessage());
        }
        int dayCount = 0;
        for (UserInfo userInfo : userInfoList) {
            Date date = userInfo.getCreated();
            long time = date.getTime();
            if (time >= this.getTodayStartTime() && time <= this.getTodayEndTime()) {
                dayCount++;
            }
        }
        userStatisticsVo.setNewUsersToday(dayCount);
        //昨日新增用户数量
        List<UserInfo> userInfos = userInfoMapper.selectList(null);
        if (CollUtil.isEmpty(userInfos)) {
            throw new BusinessException(ErrorResult.error().getErrMessage());
        }
        int yesterdayCount = 0;
        for (UserInfo userInfo : userInfoList) {
            Date date = userInfo.getCreated();
            long time = date.getTime();
            System.out.println(time);
            if (time >= this.getYesterdayStartTime() && time <= this.getYesterdayEndTime()) {
                yesterdayCount++;
            }
        }
        //今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
        int add = 0;
        if (yesterdayCount == 0) {
            add = (dayCount - yesterdayCount) / 1;
        } else {
            add = (dayCount - yesterdayCount) / yesterdayCount * 1;
        }
        userStatisticsVo.setNewUsersTodayRate(add);
        //今日活跃用户/今日登录次数
        QueryWrapper<Log> wrapper = new QueryWrapper<>();
        wrapper.between("log_time", todayStart, todayEnd);
        Integer todayLogin = logMapper.selectCount(wrapper);
        userStatisticsVo.setActiveUsersToday(todayLogin);
        userStatisticsVo.setLoginTimesToday(todayLogin);
        //昨日活跃用户/昨日登录次数
        QueryWrapper<Log> yesterdaywrapper = new QueryWrapper<>();
        yesterdaywrapper.between("log_time", yesterdayStart, yesterdayEnd);
        Integer yesterdayLogin = logMapper.selectCount(yesterdaywrapper);
        //今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        int active = 0;
        if (yesterdayCount == 0) {
            active = (todayLogin - yesterdayLogin) / 1;
        } else {
            active = (todayLogin - yesterdayLogin) / yesterdayLogin * 1;
        }
        userStatisticsVo.setNewUsersTodayRate(active);
        //今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
        userStatisticsVo.setLoginTimesTodayRate(active);

        return userStatisticsVo;

    }

    //获取当天开始时间
    private Long getTodayStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime().getTime();
    }

    //获取今天结束时间
    private Long getTodayEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime().getTime();
    }

    //获取昨天开始时间
    private Long getYesterdayStartTime() {
        Calendar yesterdayStart = Calendar.getInstance();
        yesterdayStart.set(Calendar.HOUR_OF_DAY, -24);
        return yesterdayStart.getTime().getTime();
    }

    //获取昨天结束时间
    private Long getYesterdayEndTime() {
        Calendar yesterdayEnd = Calendar.getInstance();
        yesterdayEnd.set(Calendar.HOUR_OF_DAY, 0);
        yesterdayEnd.set(Calendar.MINUTE, 0);
        yesterdayEnd.set(Calendar.SECOND, 0);
        yesterdayEnd.set(Calendar.MILLISECOND, -1);
        return yesterdayEnd.getTime().getTime();
    }

    //获取前天开始时间
    private Long getBeforeStartTime() {
        Calendar beforeStart = Calendar.getInstance();
        beforeStart.set(Calendar.HOUR_OF_DAY, -48);
        return beforeStart.getTime().getTime();
    }

    //获取前天结束时间
    private Long getBeforeEndTime() {
        Calendar beforeEnd = Calendar.getInstance();
        beforeEnd.set(Calendar.HOUR_OF_DAY, -24);
        beforeEnd.set(Calendar.MINUTE, 0);
        beforeEnd.set(Calendar.SECOND, 0);
        beforeEnd.set(Calendar.MILLISECOND, -1);
        return beforeEnd.getTime().getTime();
    }

    //获取一周开始时间
    private Long getWeekStartTime() {
        Calendar weekStart = Calendar.getInstance();
        weekStart.set(Calendar.HOUR_OF_DAY, -24 * 7);
        return weekStart.getTime().getTime();
    }

    //获取一个月开始时间
    private Long getMonthStartTime() {
        Calendar monthStart = Calendar.getInstance();
        monthStart.set(Calendar.HOUR_OF_DAY, -24 * 30);
        return monthStart.getTime().getTime();
    }

    /**
     * 年度统计数据
     *
     * @param sd
     * @param ed
     * @param type
     * @return
     */
    public YearStatisticsVo getStatistics(Long sd, Long ed, Integer type) {
        //构建返回值
        YearStatisticsVo vo = new YearStatisticsVo();
        if(type == 101){
            String start = new SimpleDateFormat("yyyy-MM-dd").format(new Date(sd));
            String end = new SimpleDateFormat("yyyy-MM-dd").format(new Date(ed));
            //获取一年前开始时间，结束时间
            String lsd = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.offsetMonth(new Date(sd), -12));
            String led = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.offsetMonth(new Date(ed), -12));
            //构建条件--1
            LambdaQueryWrapper<Analysis> wrapperA = new LambdaQueryWrapper<>();
            wrapperA.between(Analysis::getRecordDate,start,end);
            //查询 --1
            List<Analysis> analysesList = analysisMapper.selectList(wrapperA);
            if (CollUtil.isEmpty(analysesList)) {
                return new YearStatisticsVo();
            }
            //遍历集合，封装数据
            List<DateVo> thisYear = new ArrayList<>();
            for (Analysis analysis : analysesList) {
                DateVo dateVo = new DateVo();
                dateVo.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                dateVo.setAmount(analysis.getNumRegistered());
                thisYear.add(dateVo);
            }

            //构建条件--2
            LambdaQueryWrapper<Analysis> wrapperB = new LambdaQueryWrapper<>();
            wrapperB.between(Analysis::getRecordDate, lsd,led);
            //查询 --2
            List<Analysis> list2 = analysisMapper.selectList(wrapperB);
            if (CollUtil.isEmpty(list2)) {
                return new YearStatisticsVo();
            }
            //遍历,封装数据
            List<DateVo> lastYear = new ArrayList<>();
            for (Analysis analysis : list2) {
                DateVo dateVo = new DateVo();
                dateVo.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                dateVo.setAmount(analysis.getNumRegistered());
                lastYear.add(dateVo);
            }

            vo.setThisYear(thisYear);
            vo.setLastYear(lastYear);
        }
        if(type == 102){
            String start = new SimpleDateFormat("yyyy-MM-dd").format(new Date(sd));
            String end = new SimpleDateFormat("yyyy-MM-dd").format(new Date(ed));
            //获取一年前开始时间，结束时间
            String lsd = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.offsetMonth(new Date(sd), -12));
            String led = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.offsetMonth(new Date(ed), -12));
            //构建条件--1
            LambdaQueryWrapper<Analysis> wrapperA = new LambdaQueryWrapper<>();
            wrapperA.between(Analysis::getRecordDate,start,end);
            //查询 --1
            List<Analysis> analysesList = analysisMapper.selectList(wrapperA);
            if (CollUtil.isEmpty(analysesList)) {
                return new YearStatisticsVo();
            }
            //遍历集合，封装数据
            List<DateVo> thisYear = new ArrayList<>();
            for (Analysis analysis : analysesList) {
                DateVo dateVo = new DateVo();
                dateVo.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                dateVo.setAmount(analysis.getNumActive());
                thisYear.add(dateVo);
            }

            //构建条件--2
            LambdaQueryWrapper<Analysis> wrapperB = new LambdaQueryWrapper<>();
            wrapperB.between(Analysis::getRecordDate, lsd,led);
            //查询 --2
            List<Analysis> list2 = analysisMapper.selectList(wrapperB);
            if (CollUtil.isEmpty(list2)) {
                return new YearStatisticsVo();
            }
            //遍历,封装数据
            List<DateVo> lastYear = new ArrayList<>();
            for (Analysis analysis : list2) {
                DateVo dateVo = new DateVo();
                dateVo.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                dateVo.setAmount(analysis.getNumActive());
                lastYear.add(dateVo);
            }

            vo.setThisYear(thisYear);
            vo.setLastYear(lastYear);
        }
        if(type == 103){
            String start = new SimpleDateFormat("yyyy-MM-dd").format(new Date(sd));
            String end = new SimpleDateFormat("yyyy-MM-dd").format(new Date(ed));
            //获取一年前开始时间，结束时间
            String lsd = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.offsetMonth(new Date(sd), -12));
            String led = new SimpleDateFormat("yyyy-MM-dd").format(DateUtil.offsetMonth(new Date(ed), -12));
            //构建条件--1
            LambdaQueryWrapper<Analysis> wrapperA = new LambdaQueryWrapper<>();
            wrapperA.between(Analysis::getRecordDate,start,end);
            //查询 --1
            List<Analysis> analysesList = analysisMapper.selectList(wrapperA);
            if (CollUtil.isEmpty(analysesList)) {
                return new YearStatisticsVo();
            }
            //遍历集合，封装数据
            List<DateVo> thisYear = new ArrayList<>();
            for (Analysis analysis : analysesList) {
                DateVo dateVo = new DateVo();
                dateVo.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                dateVo.setAmount(analysis.getNumRetention1d());
                thisYear.add(dateVo);
            }

            //构建条件--2
            LambdaQueryWrapper<Analysis> wrapperB = new LambdaQueryWrapper<>();
            wrapperB.between(Analysis::getRecordDate, lsd,led);
            //查询 --2
            List<Analysis> list2 = analysisMapper.selectList(wrapperB);
            if (CollUtil.isEmpty(list2)) {
                return new YearStatisticsVo();
            }
            //遍历,封装数据
            List<DateVo> lastYear = new ArrayList<>();
            for (Analysis analysis : list2) {
                DateVo dateVo = new DateVo();
                dateVo.setTitle(new SimpleDateFormat("yyyy-MM-dd").format(analysis.getRecordDate()));
                dateVo.setAmount(analysis.getNumRetention1d());
                lastYear.add(dateVo);
            }

            vo.setThisYear(thisYear);
            vo.setLastYear(lastYear);
        }
        return vo;
    }
}
